/*
 * @lc app=leetcode.cn id=1049 lang=cpp
 *
 * [1049] 最后一块石头的重量 II
 */

// @lc code=start
class Solution
{
public:
  int lastStoneWeightII(vector<int>& stones)
  {
    int n = stones.size(), sum = 0;
    for (int& w : stones)
      sum += w;
    int capacity = sum / 2;
    vector<int> dp(capacity + 1);
    for (int i = 0; i < n; ++i) {
      for (int j = capacity; j >= stones[i]; --j)
        dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]);
    }
    return sum - 2 * dp[capacity];
  }
};
// @lc code=end
